package com.hnkywl.sts.action.htdygl;

import com.hnkywl.sts.entity.htgl.Htdy;
import com.hnkywl.sts.service.htdygl.HtdyService;
import com.hnkywl.sts.service.htdygl.DynaFormService;
import com.hnkywl.sts.service.organ.LjwhService;
import net.ruixin.web.struts2.SimpleActionSupport;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.hibernate.Hibernate;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: nianjunyan
 * Date: 13-4-11
 * Time:  上午 11:28
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/htdygl/htdy")
public class HtdyAction extends SimpleActionSupport {

    // 合同定义service
    private HtdyService htdyService;

    // 路径service
    private LjwhService ljwhService;

    // 合同实体
    private Htdy htdy;

    // 修改和删除合同时，合同定义id
    private String htdyId;

    // 查看合同定义html的合同定义id
    private String detailId;

    // 读取上传html
    private File htdyHtml;

    // 判断文件类型
    private String fileType;

    // 合同类型
    private String htlx;

    // 分页数
    private int page;

    // 分页组件 页面大小
    private int rows;

    // 合同定义的查询分页显示
    @Action("htdyList")
    public void htdyList() {
        try {
            this.renderJson(this.htdyService.findAllHtdy(page, rows));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }

    }

    // 合同元素定义，查询时加载合同定义
    @Action("comboboxHtdyList")
    public void comboboxHtdyList() {
        try {
            this.renderJson(this.htdyService.findAllHtdyByHtlx(htlx));
        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }

    }

    // 查询信息，修改时带出值
    @Action("htdy_content")
    public String htdyContent() {

        if (htdyId != null) {
            htdy = this.htdyService.findHtdyById(htdyId);
        }
        return SUCCESS;
    }

    // 查看合同html详细
    @Action("htdyDetail")
    public void htdyDetail() throws IOException {
        Htdy htdyDetail = this.htdyService.findHtdyById(detailId);
        if (null != htdyDetail) {
            this.renderHtml(dynaFormService.getFormHtml(htdyDetail, null));
        } else {
            this.renderHtml("没有合同模板");
        }
    }


    // 新增合同定义以及元素
    @Action("addHtdy")
    public void addHtdy() {

        // 判断上传文件是否为空，并且是htm或者html
        if (StringUtils.isEmpty(fileType) || this.htdyHtml == null || this.htdyHtml.length() == 0) {
            renderText("{\"statusCode\":\"300\", \"message\":\"" + "上传文件不能为空！" + "\"}");
            return;
        } else {
            if (!fileType.equals("htm") && !fileType.equals("html")) {
                renderText("{\"statusCode\":\"300\", \"message\":\"" + "上传文件格式不对，请上传htm或者html！" + "\"}");
                return;
            } else {
                // 保存数据
                saveHtml(htdyId);
            }
        }

    }

    // 修改合同定义以及元素
    @Action("modifyHtdy")
    public void modifyHtdy() {

        if (StringUtils.isNotEmpty(htdyId)) {

            // 判断上传文件是否为空，并且是htm或者html
            if (StringUtils.isEmpty(fileType) || this.htdyHtml == null || this.htdyHtml.length() == 0) {
                // 如果附件为空，只修改合同定义
                this.htdyService.UpdateHtdy(htdy);
                renderText("{\"statusCode\":\"200\", \"message\":\"" + "修改合同定义成功！" + "\"}");
            } else {
                if (!fileType.equals("htm") && !fileType.equals("html")) {
                    renderText("{\"statusCode\":\"300\", \"message\":\"" + "上传文件格式不对，请上传htm或者html！" + "\"}");
                    return;
                } else {
                    // 保存数据
                    saveHtml(htdyId);
                }
            }
        }

    }


    // 删除合同定义
    @Action("deleteHtdy")
    public void deleteHtdy() {
        try {
            if (StringUtils.isNotEmpty(htdyId)) {
                //判断合同是否已经被使用，使用不能进行删除
                if (null != this.htdyService.findHtdyById(htdyId).getHtwbList() && this.htdyService.findHtdyById(htdyId).getHtwbList().size() > 0) {
                    renderJson("{\"statusCode\":\"300\", \"message\":\"" + "合同定义已经产生文本不能进行删除！" + "\"}");
                } else {
                    // 判断路劲是否引用了合同定义
                    List ljList = this.ljwhService.findLjByHtdyId(htdyId);
                    if (null != ljList && ljList.size() > 0) {
                        renderJson("{\"statusCode\":\"300\", \"message\":\"" + "合同定义已经关联路劲，先删除路劲，才能删除合同定义！" + "\"}");
                    } else {
                        this.htdyService.deleteHtdy(htdyId);
                        renderJson("{\"statusCode\":\"200\", \"message\":\"删除合同定义成功!\"}");
                    }
                }

            } else {
                renderJson("{\"statusCode\":\"300\", \"message\":\"删除合同定义的id为空!\"}");
            }

        } catch (Exception e) {
            e.printStackTrace();
            renderJson("{\"statusCode\":\"300\", \"message\":\"" + e.getMessage() + "\"}");
        }
    }

    /**
     * 保存上传的html
     */
    private void saveHtml(String hId) {

        // 获取表字段
        List htnrColumns = this.htdyService.findAllColumns();

        // 合同定义
        String htdyHtml = getHtml();
        // 获取html
        if (StringUtils.isEmpty(htdyHtml)) {
            renderText("{\"statusCode\":\"300\", \"message\":\"" + "获取html错误！" + "\"}");
        } else {
            //获取html元素
            List<List> htysList = getHtys(htdyHtml);
            if (null == htysList) {
                renderText("{\"statusCode\":\"300\", \"message\":\"" + "获取获取合同元素错误！" + "\"}");
            } else {
                htdy.setDateCreated(new Date());
                htdy.setHtml(htdyHtml);
                this.htdyService.saveHtdy(htdy, htysList, hId, htnrColumns);
                //判断新增还是修改
                if (null == hId) {
                    renderText("{\"statusCode\":\"200\", \"message\":\"添加合同定义以及合同元素成功!\"}");
                } else {
                    renderText("{\"statusCode\":\"200\", \"message\":\"修改合同定义以及合同元素成功!\"}");
                }
            }
        }
    }

    /**
     * 获取html
     *
     * @return
     */
    private String getHtml() {

        // 定义流
        InputStreamReader reader = null;
        BufferedReader bufferedReader = null;

        try {
            // 读取文件
            reader = new InputStreamReader(new FileInputStream(htdyHtml), "GBK");
            bufferedReader = new BufferedReader(reader);
            StringBuffer stringBuffer = new StringBuffer();

            // 元素前缀
            String elem = "htdy_";
            if (this.htdyHtml != null && this.htdyHtml.length() != 0) {
                String fileString = "";
                while ((fileString = bufferedReader.readLine()) != null) {
                    // 把String类型的html 转换成Document对象，以便获取其中的input
                    Document doc = Jsoup.parse(fileString);
                    Elements elements = doc.select("input[name]");
                    elements.attr("type");
                    // 把input名称加前缀
                    if (elements != null && elements.size() > 0) {
                        for (int i = 0; i < elements.size(); i++) {
                            stringBuffer.append(fileString.replace(elements.get(0).attr("name"), elem + elements.get(0).attr("name")));
                        }
                    } else {
                        stringBuffer.append(fileString);
                    }

                    stringBuffer.append(System.getProperty("line.separator"));
                }

                return stringBuffer.toString();

            }

        } catch (Exception e) {
            return null;
        } finally {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 获取合同元素
     *
     * @param Htydhtml
     * @return
     */
    private List<List> getHtys(String Htydhtml) {

        // 存放合同定义元素名称
        List<List> retList = new ArrayList<List>();  //返回值, 第一个node是 name 数组, 第二个node是id 数组
        List<String> htysNameList = new ArrayList<String>(); //id 数组
        List<String> htysTitleList = new ArrayList<String>(); //name 数组

        Document doc = Jsoup.parse(Htydhtml);
        Elements elements = doc.select("input[name],textarea");


        String titleTmp;
        if (elements != null && elements.size() > 0) {
            for (int i = 0; i < elements.size(); i++) {
                if (!elements.get(i).attr("type").equals("hidden")) {
                    htysNameList.add(elements.get(i).attr("name"));

                    //获取title
                    do {
                        titleTmp = "";
                        // 第一种方案　有title属性
                        titleTmp = elements.get(i).attr("title");
                        if (titleTmp != null && !"".equals(titleTmp)) {
                            break;
                        }

                        // 第二种方案　其前有th值
                        if (elements.get(i).parent().previousElementSibling() != null && "th".equals(elements.get(i).parent().previousElementSibling().tag().getName())) {
                            titleTmp = elements.get(i).parent().previousElementSibling().text();
                            if (!"".equals(titleTmp)) {
                                break;
                            }
                        }
                        // 第三种方案　其标签有值
                        titleTmp = elements.get(i).parent().text();
                        if (titleTmp != null && !"".equals(titleTmp)) {
                            break;
                        }
                        // 第四种方案　其前一个标签的文本
                        if (elements.get(i).parent().parent() != null && elements.get(i).parent().parent().previousElementSibling() != null) {
                            titleTmp = elements.get(i).parent().parent().previousElementSibling().text();
                            if (titleTmp != null && !"".equals(titleTmp)) {
                                break;
                            }
                        }

                        //都不存存，使去name值
                        if ("".equals(titleTmp)) {
                            titleTmp = elements.get(i).attr("name");
                        }
                    }
                    while (false);

                    htysTitleList.add(titleTmp);
                }
            }
        }

        if (htysNameList.size() == 0) {
            return null;
        } else {
            retList.add(htysNameList);
            retList.add(htysTitleList);
        }
        return retList;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public int getRows() {
        return rows;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    public File getHtdyHtml() {
        return htdyHtml;
    }

    public void setHtdyHtml(File htdyHtml) {
        this.htdyHtml = htdyHtml;
    }

    public Htdy getHtdy() {
        return htdy;
    }

    public void setHtdy(Htdy htdy) {
        this.htdy = htdy;
    }

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }

    public String getDetailId() {
        return detailId;
    }

    public void setDetailId(String detailId) {
        this.detailId = detailId;
    }

    public String getHtdyId() {
        return htdyId;
    }

    public void setHtdyId(String htdyId) {
        this.htdyId = htdyId;
    }

    public String getHtlx() {
        return htlx;
    }

    public void setHtlx(String htlx) {
        this.htlx = htlx;
    }

    @Autowired
    public void setHtdyService(HtdyService htdyService) {
        this.htdyService = htdyService;
    }

    private DynaFormService dynaFormService;

    @Autowired
    public void setDynaFormService(DynaFormService dynaFormService) {
        this.dynaFormService = dynaFormService;
    }

    @Autowired
    public void setLjwhService(LjwhService ljwhService) {
        this.ljwhService = ljwhService;
    }
}
